<template>
  <div class="settings-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <el-button type="primary" icon="el-icon-plus" @click="doAdd">新增角色</el-button>

            <!-- 表格 -->
            <el-table :data="roleList" style="width: 100%">
              <el-table-column label="序号" type="index" :index="indexMethod" />
              <el-table-column label="角色名称" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="success" @click="doAssign(scope.row.id)">分配权限</el-button>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                :current-page="page"
                :page-sizes="[4, 6, 8, 10]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 弹窗 -->
        <el-dialog
          :title=" isEdit ? '编辑角色': '新增角色'"
          :visible.sync="dialogFormVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="true"
          @close="resetForm"
        >
          <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" style="width: 80%;" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="form.description" style="width: 80%;" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="doSubmit">确 定</el-button>
            <el-button @click="dialogFormVisible = false">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 分配权限弹窗 -->
        <el-dialog
          v-if="showDialogAssign"
          title="分配权限"
          :visible.sync="showDialogAssign"
          :close-on-click-modal="false"
          :close-on-press-escape="true"
        >
          <assignPermission :id="id" :show-dialog-assign.sync="showDialogAssign" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { deleteRole, getRoleList, addRole, eidtRole } from '@/api/settings'
import assignPermission from './assignPermission.vue'

export default {
  components: {
    assignPermission
  },
  data() {
    return {
      id: '',
      showDialogAssign: false, // 分配权限对话框
      activeName: 'first',
      roleList: [], // 角色列表
      page: 1, // 当前页
      pagesize: 4, // 每页条数
      total: 0, // 总条数
      dialogFormVisible: false,
      form: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }
        ]
      },
      isEdit: false
    }
  },
  created() {
    this.loadRoleList()
  },
  methods: {
    // 渲染角色列表
    async loadRoleList() {
      const res = await getRoleList({ page: this.page, pagesize: this.pagesize })
      console.log('角色列表', res)
      this.roleList = res.data.rows
      this.total = res.data.total
    },
    // 点击编辑角色按钮
    handleEdit(index, row) {
      console.log(index, row)
      this.isEdit = true
      this.dialogFormVisible = true
      this.form = { ...row }
    },
    // 点击添加角色按钮
    doAdd() {
      this.isEdit = false
      this.dialogFormVisible = true
    },
    // 删除角色
    handleDelete(index, row) {
      console.log(index, row)

      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRole(row.id)
        // this.total % this.pagesize === 1
        if (this.roleList.length === 1) {
          this.page <= 1 ? this.page = 0 : this.page--
        }
        this.$message.success('删除成功')
        this.loadRoleList()
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 从第一页开始发请求
      this.page = 1
      this.pagesize = val
      this.loadRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadRoleList()
    },
    // 点击表单中的确认按钮
    doSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          this.isEdit ? await this.doEditRole() : await this.doAddRole()
          this.loadRoleList()
          this.dialogFormVisible = false
        }
      })
    },
    async doEditRole() {
      await eidtRole(this.form)
      this.$message.success('编辑成功')
    },
    async doAddRole() {
      await addRole(this.form)
      // this.page = this.total % this.pagesize + 1
      this.total++
      this.page = Math.ceil(this.total / this.pagesize)
      this.$message.success('新增成功')
    },
    // 表格第一列数字
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + 1 + index
    },
    // 清空表单
    resetForm() {
      this.$refs.formRef.resetFields()
      // 清空form
      for (const k in this.form) {
        this.form[k] = ''
      }
    },
    // 分配权限
    doAssign(id) {
      this.showDialogAssign = true
      this.id = id
    }
  }
}
</script>

<style lang="scss" scoped>
.pagination{
  text-align: center;
  margin-top: 20px;
}
</style>
